<template>
  <header-component /> 
  <div class="container">
    <h2>Order Processing</h2>
    <div class="tabs">
      <div
        class="tab"
        :class="{ active: currentTab === 'orderInfo' }"
        @click="showTab('orderInfo')"
      >
        Order Items
      </div>
      <div
        class="tab"
        :class="{ active: currentTab === 'paymentInfo' }"
        @click="showTab('paymentInfo')"
      >
        Payment Info
      </div>
      <div
        class="tab"
        :class="{ active: currentTab === 'shippingInfo' }"
        @click="showTab('shippingInfo')"
      >
        Shipping Info
      </div>
    </div>

    <form @submit.prevent="handleSubmit">
      <!-- order info -->
      <div v-show="currentTab === 'orderInfo'" class="tab-content">
        <h3>Your Cart Items</h3>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <i class="fas fa-spinner fa-spin"></i> Loading cart items...
        </div>

        <!-- 错误状态 -->
        <div v-else-if="error" class="error-state">
          ❌ {{ error }}
          <button @click="fetchCartData">Retry</button>
        </div>

        <!-- 成功加载数据 -->
        <template v-else>
          <table v-if="cartItems.length > 0">
            <thead>
              <tr>
                <th>Item ID</th>
                <th>Product</th>
                <th>Qty</th>
                <th>Unit Price</th>
                <th>Total</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in cartItems" :key="item.itemId">
                <td>{{ item.itemId }}</td>
                <td>
                  {{ item.item.attribute1 || item.item.productId }}
                  <span class="product-id">({{ item.item.productId }})</span>
                </td>
                <td>{{ item.number }}</td>
                <td>{{ formatPrice(item.item.listPrice) }}</td>
                <td>{{ formatPrice(item.number * item.item.listPrice) }}</td>
              </tr>
            </tbody>
            <tfoot>
              <tr>
                <td colspan="4" class="total-label">Subtotal:</td>
                <td class="total-value">{{ formatPrice(subtotal) }}</td>
              </tr>
              <tr>
                <td colspan="7">Final Total after Coupon: {{ formatCurrency(finalTotal) }}</td>
          </tr>
            </tfoot>
          </table>

          <!-- 空购物车提示 -->
          <div v-else class="empty-cart">Your cart is currently empty</div>
        </template>

        <!-- 处理按钮 -->
        <div class="actions">
          <button
            type="button"
            @click="currentTab = 'paymentInfo'"
            :disabled="loading || error || cartItems.length === 0"
          >
            Proceed to Payment
          </button>
        </div>
      </div>

      <!-- Payment Info -->
      <div v-show="currentTab === 'paymentInfo'" class="tab-content">
        <h3>Payment Info</h3>
        <label>Card Type</label>
        <select v-model="order.cardType" required>
          <option value="Visa">Visa</option>
          <option value="MasterCard">MasterCard</option>
        </select>
        <label>Credit Card Number</label>
        <input v-model="order.creditCard" required />
        <label>Expiry Date</label>
        <input v-model="order.expiryDate" required />
        <button type="button" @click="showTab('shippingInfo')">Proceed to Shipping</button>
      </div>

      <!-- Shipping Info -->
      <div v-show="currentTab === 'shippingInfo'" class="tab-content">
        <h3>Shipping Info</h3>
        <label>First Name</label>
        <input v-model="order.shipToFirstName" required />
        <label>Last Name</label>
        <input v-model="order.shipToLastName" required />
        <label>Address</label>
        <input v-model="order.shipAddress1" required />
        <label>City</label>
        <input v-model="order.shipCity" required />
        <label>State</label>
        <input v-model="order.shipState" />
        <label>ZIP Code</label>
        <input v-model="order.shipZip" />
        <button type="submit">Confirm Order</button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { submitOrder } from "@/api/order";
import request from "@/utils/request";

const route = useRoute();
const router = useRouter();
// 响应式数据
const cartItems = ref([]);
const subtotal = ref(0);
console.log("History state:", history.state);
const finalTotal = ref(0);
//const subTotal = ref(0);
//const passedFinalTotal = ref(history.state?.finalTotal ?? 0);
const couponList = ref(history.state?.couponList ?? []);
//const subTotal = ref(Number(history.state?.subTotal ?? 0)); // ✅ 强制转换为数字
//const passedFinalTotal = ref(history.state?.finalTotal ?? 0);
//const finalTotal = computed(() => passedFinalTotal.value);
const loading = ref(true);
const error = ref(null);
const currentTab = ref("orderInfo");
const selectedCouponId = ref(Number(route.query.couponId) || null);
const username = ref(localStorage.getItem("username") || ""); // 从本地取出用户名
const order = ref({
  cardType: "Visa",
  creditCard: "999 9999 9999 9999",
  expiryDate: "4/19",
  shipToFirstName: "",
  shipToLastName: "",
  shipAddress1: "",
  shipCity: "",
  shipState: "",
  shipZip: "",
});



// 价格格式化
const formatPrice = (price) => {
  const numericPrice = Number(price) || 0;
  return `$${numericPrice.toFixed(2)}`;
};

const formatCurrency = (value) => {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
  }).format(value);
};

// 获取购物车数据
const fetchCartData = async () => {
  try {
    loading.value = true;
    error.value = null;

    const response = await request.get("/cart");
    console.log("购物车数据：", response.data);  // 打印完整的购物车数据
    if (response.status !== 0) {
      throw new Error(response.message);
    }
    // 确保 cartItems 里有有效的 item 数据
    const rawItems = response.data?.cartItems || [];
    rawItems.forEach(item => {
      console.log("检查 cartItem:", item);  // 打印每个 cartItem，查看 item 是否为空
    });

    // 过滤无效的 cartItem（item 为 null 的项）
    const validItems = rawItems.filter(ci => ci.item && ci.item.productId);
    if (validItems.length === 0) {
      throw new Error("购物车中没有有效的商品！");
    }

    console.log("有效购物车项：", validItems);  // 确保有效项都包含商品信息

    cartItems.value = validItems;
    subtotal.value = response.data.total;

  } catch (err) {
    console.error("购物车加载失败:", err);
    error.value = err.message;
  } finally {
    loading.value = false;
  }
};


//获取用户信息
const fetchUserInfo = async () => {
  try {
    if (!username.value) {
      throw new Error("Username not found in local storage.");
    }

    const response = await request.get(`/information/${username.value}`, {
      headers: {
        Authorization: localStorage.getItem("token"),
      },
    });

    if (response.status !== 0) {
      throw new Error(response.message);
    }

    const data = response.data;
    order.value.shipToFirstName = data.firstName;
    order.value.shipToLastName = data.lastName;
    order.value.shipAddress1 = data.address1;
    order.value.shipCity = data.city;
    order.value.shipState = data.state;
    order.value.shipZip = data.zip;

  } catch (err) {
    console.error("用户信息获取失败：", err);
    alert("加载用户信息失败：" + err.message);
  }
};

// const finalTotal = computed(() => {
//   const coupon = couponList.value.find(c => c.id === selectedCouponId.value);
//   if (!coupon || subTotal.value < coupon.limit) return subTotal.value;

//   if (coupon.deduction > 0) {
//     return Math.max(subTotal.value - coupon.deduction, 0);
//   }

//   if (coupon.discount > 0) {
//     return subTotal.value * coupon.discount;
//   }

//   return subTotal.value;
// });

// 提交订单
const handleSubmit = async () => {
  try {
    if (!username.value) {
      alert("Please login to place order");
      return;
    }
    if (cartItems.value.length === 0) {
      alert("您的购物车为空，无法提交订单！");
      return;
    }

    const requestData = {
      cardType: order.value.cardType,
      creditCard: order.value.creditCard,
      expiryDate: order.value.expiryDate,
      shipToFirstName: order.value.shipToFirstName,
      shipToLastName: order.value.shipToLastName,
      shipAddress2: order.value.shipAddress1,  // 注意后端使用的是 address2
      shipCity: order.value.shipCity,
      shipState: order.value.shipState,
      shipZip: order.value.shipZip,
    };

    const response = await request.post(`/orders/confirm/${username.value}`, requestData);

     //  清空购物车
     const clearCartResponse = await request.delete('/cart/clear');
    if (clearCartResponse.data.status !== 0) {
      console.warn('订单提交成功，但清空购物车失败:', clearCartResponse.data.message);
      // 测试
    } else {
      console.log('购物车已成功清空');
    }

    if (response.status !== 0) {
      throw new Error("订单确认失败：" + response.data.message);
    }

    alert("订单已成功提交！");
    router.push("/ordersuccess"); // 成功页路由跳转

  } catch (err) {
    console.error("订单确认失败:", err);
    alert(`订单确认失败：${err.message}`);
  }
};

// 切换标签页
const showTab = (tab) => {
  currentTab.value = tab;
};

// 生命周期钩子(初始化加载)
onMounted(() => {
  fetchCartData();
  fetchUserInfo();
  selectedCouponId.value = Number(route.query.couponId || null);
  const checkoutData = sessionStorage.getItem('checkoutData');
  if (checkoutData) {
    const data = JSON.parse(checkoutData);
    finalTotal.value = data.finalTotal || 0;
    subtotal.value = data.subTotal || 0;
    // 设置其他状态...
    sessionStorage.removeItem('checkoutData'); // 清理数据
  }
});
</script>


<style scoped>
/* 页面整体样式 */
body {
  font-family: "Helvetica Neue", Arial, sans-serif;
  margin: 0;
  padding: 0;
  background-color: #f9f9f9;
}

.container {
  width: 70%;
  margin: 30px auto;
  padding: 20px 30px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

h2 {
  text-align: center;
  color: #734012;
  font-size: 28px;
  margin-bottom: 30px;
}

.tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
  border-bottom: 2px solid #ddd;
}

.tab {
  padding: 10px 20px;
  cursor: pointer;
  font-weight: bold;
  color: #555;
  transition: color 0.3s ease, border-bottom 0.3s ease;
}

.tab.active {
  border-bottom: 3px solid #fccc1c;
  color: #734012;
}

.tab:hover {
  color: #734012;
}


.tab-content.active {
  display: block;
}

/* 表格样式 */
table {
  border-collapse: separate;
  border-spacing: 12px;
  width: 100%;
  margin: 20px 0;
}

td,
th {
  padding: 12px 16px;
  text-align: center;
  vertical-align: middle;
  background-color: #fffbe6;
  border-radius: 8px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

th {
  font-weight: bold;
  background-color: #fccc1c;
  color: #734012;
  text-transform: uppercase;
}

tr:hover {
  transform: scale(1.02);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
}

tr:nth-child(odd) td {
  background-color: rgba(252, 204, 28, 0.15);
}

tr:nth-child(even) td {
  background-color: rgba(252, 204, 28, 0.2);
}

input,
select {
  width: 100%;
  padding: 10px;
  margin: 10px 0;
  border-radius: 8px;
  border: 1px solid #ddd;
}

button {
  background-color: #fccc1c;
  color: white;
  font-size: 16px;
  padding: 12px 20px;
  border: none;
  cursor: pointer;
  border-radius: 8px;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #734012;
}
</style>
